package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2024-03-20
 * Time: 22:25
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求中的密码和用户名
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || password == null || "".equals(username) || "".equals(password)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前传过来的 username 或者 password 为空");
            return;
        }

        // 2. 和数据库进行验证，看当前这样的用户名和密码是否正确。
        UserDao userDao = new UserDao();
        User user = userDao.getUserByName(username);
        if (user == null) {
            // 当前提交的用户名或者密码有错误
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您的用户名或者密码有错误！");
            return;
        }
        if (!password.equals(user.getPassword())) {
            // 当前提交的用户名或者密码有错误
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您的用户名或者密码有错误！");
            return;
        }

        // 3. 创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);

        // 4. 跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);

        if(session == null) {
            resp.setStatus(403);
            return;
        }

        User user = (User)session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            return;
        }

        resp.setStatus(200);
    }
}
